import { ref } from "vue"

import { setColorScheme } from 'mdui/functions/setColorScheme.js';
import { removeColorScheme } from 'mdui/functions/removeColorScheme.js';

function getSysTheme() {
    // 获取系统主题
    let theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? "dark" : "light";
    return theme
}

function checkTheme(type = null, if_animate = true) {
    let theme = document.getElementById("theme")
    let is_dark = document.documentElement.classList.contains('mdui-theme-dark')
    if (type == null) {
        if (is_dark) {
            theme.icon = "light_mode"
            document.querySelector(".nav").style.borderRight = "1px solid rgb(45 45 45)"
        } else {
            theme.icon = "dark_mode"
            document.querySelector(".nav").style.borderRight = "1px solid rgb(230 230 230)"
        }
    } else {
        if (type == "dark") {
            theme.icon = "light_mode"

            changeTheme("dark", if_animate)
        } else if (type == "light") {
            theme.icon = "dark_mode"

            changeTheme("light", if_animate)
        }
    }
}

function changeTheme(type, if_animate = true, location = null) {
    let o_type = getThemeType();
    if (type === o_type) {
        return false;
    } else if (type == "auto") {
        let sTheme = getSysTheme();
        type = sTheme;
    }
    let html = document.documentElement;

    // Ensure View Transition API is supported
    if (document.startViewTransition) {
        let transition = document.startViewTransition(() => {
            if (type === "dark") {
                if (!html.classList.contains('mdui-theme-dark')) {
                    html.classList.add('mdui-theme-dark');
                    document.querySelector(".nav").style.borderRight = "1px solid rgb(45, 45, 45)";
                }
            } else if (type === "light") {
                if (html.classList.contains('mdui-theme-dark')) {
                    html.classList.remove('mdui-theme-dark');
                    document.querySelector(".nav").style.borderRight = "1px solid rgb(230, 230, 230)";
                }
            }
        });

        if (if_animate) {
            let x, y;
            if (location) {
                x = location.x;
                y = location.y;
            } else if (typeof event !== 'undefined') {
                x = event.pageX || (event.clientX + window.scrollX);
                y = event.pageY || (event.clientY + window.scrollY);
            } else {
                // Default to center if event is not available
                x = window.innerWidth / 2;
                y = window.innerHeight / 2;
            }

            //console.log({ x, y, location });

            // Calculate radius for clip path
            const radius = Math.sqrt(
                Math.max(x, window.innerWidth - x) ** 2 +
                Math.max(y, window.innerHeight - y) ** 2
            );
            let clipPath = [
                `circle(0 at ${x}px ${y}px)`,
                `circle(${radius}px at ${x}px ${y}px)`
            ];
            // Wait for transition to finish
            transition.ready.then(() => {
                // Apply the animation
                html.animate(
                    { clipPath: clipPath },
                    {
                        duration: 500,
                        pseudoElement: '::view-transition-new(root)'
                    }
                );
            }).catch(err => {
                console.error('Transition error:', err);
            });
            // Cancel the transition if it's still running
            setTimeout(() => {
                try {
                    transition.cancel();
                }
                catch (err) {
                    console.log('Transition error:', err);
                }
            }, 500);
        }
    } else {
        // Fallback for browsers that do not support the View Transition API
        console.warn('View Transition API not supported in this browser.');
        if (type === "dark") {
            html.classList.add('mdui-theme-dark');
            document.querySelector(".nav").style.borderRight = "1px solid rgb(45, 45, 45)";
        } else if (type === "light") {
            html.classList.remove('mdui-theme-dark');
            document.querySelector(".nav").style.borderRight = "1px solid rgb(230, 230, 230)";
        }
    }
}


function getThemeType() {
    let is_dark = document.documentElement.classList.contains('mdui-theme-dark')
    if (is_dark) {
        return "dark"
    } else {
        return "light"
    }
}
export default {
    toggleTheme(e) {
        let html = document.documentElement
        //html.classList.add("all-animate")
        //console.log(html.classList);
        const transition = document.startViewTransition(() => {

            html.classList.toggle('mdui-theme-dark');
            checkTheme()

        });

        const x = e.clientX
        const y = e.clientY
        // 从点击点到窗口最远边缘的距离，这个距离即为圆的半径，用于确定一个圆形裁剪路径 (clip path) 的最大尺寸，以便覆盖整个视窗。
        // 勾股定理：a² + b² = c²
        const radius = Math.sqrt(Math.max(x, (window.innerWidth - x)) ** 2 + Math.max(y, (window.innerHeight - y)) ** 2)
        let clipPath = [
            `circle(0 at ${x}px ${y}px)`,
            `circle(${radius}px at ${x}px ${y}px)`,
        ]
        let is_dark = html.classList.contains('mdui-theme-dark')
        transition.ready.then(() => {
            // 实现过渡的过程 circle
            document.documentElement.animate(
                {
                    clipPath: clipPath,
                },
                {
                    duration: 500,
                    pseudoElement: '::view-transition-new(root)',
                }
            )
        })
        // 取消过渡
        setTimeout(() => {
            transition.cancel()
        }, 500)

        //html.classList.remove("all-animate")
        //console.log(html.classList);
    },
    getThemeType: getThemeType,
    changeTheme: changeTheme,
    checkTheme: checkTheme,
    colorArr: {
        aotu: "auto",
        red: "#ffb4aa",
        purple: "#f9abff",
        blue: "#9ecaff",
        green: "#78dc77",
        yellow: "#dbc90a",
        grey: "#4fd8eb"
    },
    changeColorTheme(color) {
        if (color == "auto") {
            removeColorScheme()
        } else {
            setColorScheme(this.colorArr[color])
        }
    },
    getSysTheme: getSysTheme,
}


